import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import { getToken } from '@/utils/storage'
import Home from '@/views/Layout/Home'
import Articles from '@/views/Layout/Articles'
import Pictures from '@/views/Layout/Pictures'
import NotFound from '@/views/NotFound'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    }, {
      path: '/',
      component: Layout,
      children: [
        {
          path: '/',
          component: Home
        },
        {
          path: '/articles',
          component: Articles
        },
        {
          path: '/pictures',
          component: Pictures
        }
      ]
    },
    // * 表示匹配所有路径, 用于放最后配置 404
    { path: '*', component: NotFound }
  ]
})

// 配置路由的导航守卫
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})

export default router
